package mobi.greenplate.theweb.user;

import javax.inject.Inject;
import javax.inject.Named;
import mobi.greenplate.theweb.repository.UserRepository;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 *
 * @author dmakariev
 */
@Component("greenPlateUserAuthenticationProvider")
public class UserAuthenticationProvider implements AuthenticationProvider {

    @Inject
    @Named("userRepository")
    private UserRepository userRepository;

    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        final String userName = (String) authentication.getPrincipal();
        final String password = (String) authentication.getCredentials();
        if (true == userRepository.authenticate(userName, password)) {
            return new UserAuthentication(userName, password, userRepository.loadRoleByUserName(userName));
        }
        return null;
    }

    public boolean supports(Class<? extends Object> authentication) {
        return true;
    }
}
